/**
 *
 */
package com.ccjq.shosestore.web.controller.member;

import com.ccjq.shosestore.core.utils.UuidUtils;
import com.ccjq.shosestore.member.bo.User;
import com.ccjq.shosestore.order.bo.OrderBo;
import com.ccjq.shosestore.shoppingcart.bo.SaveCartBo;
import com.ccjq.shosestore.shoppingcart.bo.ShowCartBo;
import com.ccjq.shosestore.shoppingcart.service.ShoppingCartService;
import com.ccjq.shosestore.shoppingcart.service.impl.ShoppingCartServiceImpl;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

//import com.alibaba.fastjson.JSON;

/**
 * 购物车
 * @author 李佳鑫
 */
public class ShoppingCartServlet extends HttpServlet {

    private static final long serialVersionUID = 2158996463635419821L;
    private ShoppingCartService shoppingCart = new ShoppingCartServiceImpl();
    private static String INSERT_CART = "insert";//添加购物车
    private static String UPDATE_CART = "update";//修改商品数量
    private static String DELETE_CART = "delete";//删除指定商品
    private static String CLEAR_CART  = "clear";//跳到结算界面
    private static String ORDER_CART  = "order";//提交结算
    public void doGet(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{
        this.doPost(req, response);
    }
    public void doPost(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{
        String flag = req.getParameter("flag");
        if(StringUtils.isBlank(flag)){//如果flag是空的,直接显示该用户的购物车界面
            toShoppingCart(req,response);
        }else if(DELETE_CART.equals(flag)){//删除购物车中商品
            toDelete(req,response);
        }else if(INSERT_CART.equals(flag)){//添加商品并显示购物车
            toInsert(req,response);
        }else if(UPDATE_CART.equals(flag)){//修改购物车中商品数量
            toUpdate(req,response);
        }else if(CLEAR_CART.equals(flag)){//跳到结算界面
            toOrder(req,response);
        }else if(ORDER_CART.equals(flag)){//实现结算功能
            toClearOrder(req,response);
        }
    }
    /**
     * 不插入商品，直接显示该用户的购物车界面
     * */
    private void toShoppingCart(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        if(user == null){//如果没有登录  就去登录
            req.getRequestDispatcher("WEB-INF/jsp/member/login.jsp").forward(req, response);
        }else{
            //通过用户ID 查询购物车中商品集合和商品总价
            List<ShowCartBo> cartsList = shoppingCart.queryCartById(user.getUserid());
            double total = shoppingCart.queryTotal(user.getUserid());
            session.setAttribute("cartsList", cartsList);
            session.setAttribute("total", total);
            //跳转到购物车界面
            req.getRequestDispatcher("WEB-INF/jsp/shoppingcart/shoppingcart.jsp").forward(req, response);
        }
    }
    /**
     * 插入商品并显示购物车
     * */
    private void toInsert(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{
        HttpSession session = req.getSession();
        User u = (User) session.getAttribute("user");
        if (u != null) {
            //已登录
            SaveCartBo saveCartBo = new SaveCartBo();
            //获取前台商品ID
            String proId = req.getParameter("product_id");
            //获取前台商品数量
            String num = req.getParameter("num");
            if(num == null){//如果直接添加购物车没有数量就默认是1
                num = 1 + "";
            }
            User user = (User)session.getAttribute("user");
            //将获取到信息存到模型中
            saveCartBo.setUserId(user.getUserid());
            saveCartBo.setProductId(proId);
            saveCartBo.setQuantity(Integer.parseInt(num));

            List<ShowCartBo> cartsList = shoppingCart.saveCart(saveCartBo);
            double total = shoppingCart.queryTotal(user.getUserid());
            session.setAttribute("cartsList", cartsList);
            session.setAttribute("total", total);
            req.getRequestDispatcher("WEB-INF/jsp/shoppingcart/shoppingcart.jsp").forward(req, response);
        } else {
            // 未登录
            req.getRequestDispatcher("WEB-INF/jsp/member/login.jsp").forward(req, response);
        }
    }
    /**
     * 删除购物车中商品
     * */
    private void toDelete(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{
        HttpSession session = req.getSession();
        //得到共享的user  取出userId
        User user = (User)session.getAttribute("user");
        if(user != null){
            //得到商品对应的购物车ID  通过路径拼参数带过来shopCartId
            String shopCartId = req.getParameter("shopCartId");
            shoppingCart.delCartById(shopCartId);
            //删除之后再显示购物车页面
            List<ShowCartBo> cartsList = shoppingCart.queryCartById(user.getUserid());
            double total = shoppingCart.queryTotal(user.getUserid());
            session.setAttribute("cartsList", cartsList);
            session.setAttribute("total", total);
            req.getRequestDispatcher("WEB-INF/jsp/shoppingcart/shoppingcart.jsp").forward(req, response);
        }else{
            //未登录
            req.getRequestDispatcher("WEB-INF/jsp/member/login.jsp").forward(req, response);
        }
    }
    /**
     * 跳到结算界面
     * */
    private void toOrder(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{
        HttpSession session = req.getSession();
        //得到购物车商品信息的list
        @SuppressWarnings("unchecked")
        List<ShowCartBo> cartsList = (List<ShowCartBo>)session.getAttribute("cartsList");
        if(cartsList == null){//说明购物车中没有商品 提示添加商品才能结算
            req.getRequestDispatcher("WEB-INF/jsp/shoppingcart/shoppingcart.jsp").forward(req, response);
        }else{
            req.getRequestDispatcher("WEB-INF/jsp/shoppingcart/order.jsp").forward(req, response);
        }
    }
    /**
     * 修改购物车中商品数量
     * */
    private void toUpdate(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        if(user != null){
            //拆分shoppingcart.jsp的json字符串
            //{'flag':'update','stringbuffer':'id1=quan1@id2=quan2'}
            String updateInfos = req.getParameter("stringbuffer");
            String[] updateInfo = updateInfos.split("@");
            for(int i = 0;i < updateInfo.length;i++){
                String[] info = updateInfo[i].split("=");
                if(info.length == 2){
                    //info[0])：购物车ID;info[1]):数量
                    shoppingCart.updateCartById(Integer.parseInt(info[1]), info[0]);
                }
            }
        }else{
            req.getRequestDispatcher("WEB-INF/jsp/shoppingcart/order.jsp").forward(req, response);
        }
    }
    /**
     * 实现结算功能
     * */
    private void toClearOrder(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{
        HttpSession session = req.getSession();
        //得到购物车商品信息的list
        @SuppressWarnings("unchecked")
        List<ShowCartBo> cartsList = (List<ShowCartBo>)session.getAttribute("cartsList");
        //得到支付类型 2：支付宝;1:微信;
        String payment = req.getParameter("payment");
        //得到session共享的总价total
        double total = (Double)session.getAttribute("total");
        //获取结算页面的文本框值
        String receiver = req.getParameter("receiver");
        String address = req.getParameter("address");
        String province = req.getParameter("province");
        String zipcode = req.getParameter("zipcode");
        String city = req.getParameter("city");
        String telphone = req.getParameter("telphone");
        String county = req.getParameter("county");
        User user = (User)session.getAttribute("user");
        //将文本框的值存到order模块的orderBo模块中
        OrderBo orderBo = new OrderBo();
        orderBo.setOrderId(UuidUtils.generateShortUUID("o", 10));
        orderBo.setReceiver(receiver);
        orderBo.setAddress(address);
        orderBo.setProvince(province);
        orderBo.setZipcode(zipcode);
        orderBo.setCity(city);
        orderBo.setTelphone(telphone);
        orderBo.setCounty(county);
        orderBo.setAmout(total);
        //sysdate是获取数据库的系统时间   固定的
        orderBo.setCreateTime("sysdate");
        orderBo.setPayment(Integer.parseInt(payment));
        orderBo.setUserId(user.getUserid());
        List<OrderBo> ordeBoS = shoppingCart.commitOrder(cartsList,orderBo);
        if(ordeBoS.size() == 0){
            req.getRequestDispatcher("WEB-INF/jsp/shoppingcart/shoppingcart.jsp").forward(req, response);
        }else{
            req.setAttribute("orderList", ordeBoS);
            //转发到显示订单的页面
            req.getRequestDispatcher(req.getContextPath()+"/OrderServlet?flag=qoi").forward(req, response);
        }
    }
}